import os
import time

from selenium.webdriver.support.wait import WebDriverWait
from student.base import log
from student.config import DIR_PATH


class Base:

    # 初始化方法
    def __init__(self, driver):
        log.info("正在初始化，driver对象：{}".format(driver))
        self.driver = driver

    # 查找元素方法
    def base_find(self, loc, timeout=10, poll=0.5, ):
        print('-->正在查找:{}'.format(loc))
        return WebDriverWait(self.driver, timeout, poll).until(lambda x: x.find_element(*loc))

    # 点击方法
    def base_click(self, loc):
        log.info("正调用点击元素：{}".format(loc))
        self.base_find(loc).click()

    # 输入方法
    def base_input(self, loc, value):
        log.info("正调用输入元素方法：{} 输入内容：{}".format(loc, value))
        # 获取元素
        el = self.base_find(loc)
        # 清空
        el.clear()
        # 输入
        el.send_keys(value)

    # 获取文本方法
    def base_get_text(self, loc):
        log.info("正调用获取元素信息方法：{}".format(loc))
        return self.base_find(loc).text

    # 截图方法
    def ase_get_img(self):
        log.info("正调用截图方法")
        img_path = DIR_PATH + os.sep + 'img' + os.sep + "{}.png".format(time.strftime("%Y%m%d%H%M%S"))
        self.driver.get_screenshot_as_file(img_path)

    # 切换frame
    def base_switch_frame(self, loc):
        # 获取元素
        log.info("正在调用切换frame方法，切换对象：{}".format(loc))
        el = self.base_find(loc)
        # 执行切换
        self.driver.switch_to.frame(el)

    # 恢复frame
    def base_default_frame(self):
        self.driver.switch_to.default_content()

    # 切换窗口
    # 切换多窗口方法
    def base_switch_to_window(self, window_title=None):

        handles = self.driver.window_handles
        if len(handles) < 2:
            raise Exception("未找到新窗口！")

        if window_title:
            # 根据标题匹配窗口
            for handle in handles:
                self.driver.switch_to.window(handle)
                if window_title in self.driver.title:
                    return
            raise Exception(f"未找到标题包含 '{window_title}' 的窗口")
        else:
            # 默认切换到最新窗口
            self.driver.switch_to.window(handles[-1])

    def base_switch_to_new_window(self, main_window):
        all_windows = self.driver.window_handles
        for window in all_windows:
            if window != main_window:
                self.driver.switch_to.window(window)
                return window
        return None
